<?php
vendor('PHPExcel/PHPExcel');
class CommonAction extends Action{

    /**
     * @var int 加价比例
     */
    public $buyFasterRate = 30;

    /**
     * @var int 最低加价
     */
    public $buyFasterLow = 1000;

    /**
     * @var int 最高加价
     */
    public $buyFasterHigh = 2999;

    /**
     * @var 用户信息
     */
    public $member;

    /**
     * @var null 数据库对象
     */
    public $M = null;

    /**
     * @var 缓存Redis
     */
    public $redis_cache;

    /**
     * @var string 错误信息
     */
    public $errorMsg = '';

    /**
     * @var mongo对象
     */
    public $mongo;

    /**
     * @var mongodb数据库
     */
    public $mongoDb;

    public $pagestring = '';

    public $pageinfo_data = array();

    //协议列表
    public $protocol = array(
        'https' => array(),
        'http'  => array()
    );

    /**
     * 构造函数
     */
    public function __construct(){

        parent::__construct();

        $this->redis_cache_connect();
        /**
         * 链接mongo服务器
         */
        $this->mongoConnetion();


        $this->member = session('member');

        $this->now = date('Y-m-d H:i:s');
        //$this->concurrent_control();
        $this->M = D();
        $this->pageinfo_data = array(
            'title'       => C('pageinfo_title'),
            'keywords'    => C('pageinfo_keywords'),
            'description' => C('pageinfo_description'),
            'sitename'    => C('pageinfo_sitename'),

        );
        $this->webinfo = array(
            'STATION_MOBILE'        => C('STATION_MOBILE'),
            'SERVICE_WECHAT'        => C('SERVICE_WECHAT'),
            'SERVICE_EMAIL'         => C('SERVICE_EMAIL'),
            'SERVICE_TELEPHONE'     => C('SERVICE_TELEPHONE'),
            'SERVICE_ADDRESS'       => C('SERVICE_ADDRESS'),
        );
        $this->assign('pageinfo', $this->pageinfo);
        $this->assign('webinfo', $this->webinfo);
        $this->assign('member', $this->member);
        //static版本号
        $staticVersion = C('STATIC_VERSION') ? C('STATIC_VERSION') : date('YmdH');
        $this->assign('staticVersion',$staticVersion);
    }

    /**
     * mongo链接
     */
    private function mongoConnetion(){
        // 连接到 MongoDB
        //$manager = new MongoDB\Driver\Manager("mongodb://yourserver.com/", array("username" => $username, "password" => $password ) );
        $mongoUrl = C('MONGO_DB_CON');
        //echo $mongoUrl;
        //die();
        $mongo = new MongoDB\Driver\Manager($mongoUrl);
        $this->mongo = $mongo;
        // 选择mongo数据库
        $mongoDb = $mongo->dunmama;
        $this->mongoDb = $mongoDb;
    }

    /*
     * 并发访问控制
     * $concurrent_date_is 并发控制时间单位 h小时 i分 s秒 x不用
     * $concurrent_ip_times 时间段内限制次数
     */
    private function concurrent_control($concurrent_date_is='d',$concurrent_ip_times=50){
        //用户登录后
        $pc_session_login_sessionId=S('pc_session_login_sessionId'.$_SESSION['member']['id']);
        if(!empty($pc_session_login_sessionId) && session_id()!=$pc_session_login_sessionId)
        {
            session('member',null);
        }
        //并发控制时间单位 h小时 i分 s秒 x不用
        if($concurrent_date_is != 'x')
        {
            $key_date = $expire = '';
            switch (strtolower($concurrent_date_is)) {
                case 'd': //按天
                    $key_date=date('Ymd',time());
                    $expire  = 60 * 60 * 24;
                    break;
                case 'h': //按小时
                    $key_date=date('Ymdh',time());
                    $expire = 60 * 60;
                    break;
                case 'i': //按分钟
                    $key_date=date('Ymdhi',time());
                    $expire = 60;
                    break;
                case 's': //按秒
                    $key_date=date('Ymdhis',time());
                    $expire = 1;
                    break;
            }
            if(ACTION_NAME == 'loginsubmit'){
                $concurrent_ip_times = 15;
            }
            //key
            $concurrent_control_key=md5(MODULE_NAME.':'.ACTION_NAME.':'.get_client_ip().':'.$key_date);
            $concurrent_times = S($concurrent_control_key); //已有次数
            $concurrent_times = $concurrent_times + 1;
            S($concurrent_control_key,$concurrent_times,$expire);
            //时间段内访问限制
            if($concurrent_times>$concurrent_ip_times)
            {
                if($this->isAjax())
                {
                    $this->ajaxError('您的访问过于频繁,请稍后重试!');
                }else{
                    header("Content-type: text/html; charset=utf-8");
                    echo "<script>alert('您的访问过于频繁,请稍后重试!');</script>";
                    exit;
                }
            }
        }

    }
    /*
     * https强制跳转
     */
    private function _protocol_redirect(){
        $be_protocol = 'https';
        $current_protocol = (isset($_SERVER['HTTPS']) && $_SERVER['SERVER_PORT'] == '443') ? 'https' : 'http';
        if ($current_protocol == $be_protocol) {
            return false;
        }
        if (!empty($_POST)) {
            header("refresh:3;url=" . $_SERVER['HTTP_REFERER']);
            echo '请使用[' . strtoupper($be_protocol) . ']协议提交数据';
            exit;
        }
        header('HTTP/1.1 301 Moved Permanently');
        header('Location: ' . $be_protocol . '://' . DOMAIN_URI . $_SERVER['REQUEST_URI']);
        exit;
    }
    public function error_notice($message)
    {
        header("HTTP/1.1 404 Not Found");
        $this->error($message, $jumpUrl = '', $ajax = false);
    }
    public function _empty($param)
    {
        header("HTTP/1.1 404 Not Found");
        $this->error('您访问的页面不存在[' . MODULE_NAME . '~' . ACTION_NAME . ']');
    }
    public function page_limit()
    {
        $limitstr = ($this->M->page['no'] - 1) * $this->M->page['num'] . ',' . $this->M->page['num'];
        return $limitstr;
    }
    public function set_pages($pageurl)
    {
        $this->setPagesHtml($pageurl, 'Public:page');
    }

    /**
     * 设置只有上一页下一页的分页提示
     */
    public function setPagesOnlyPrevNext($pageurl)
    {
        $this->setPagesHtml($pageurl, 'Public:only_pn_page');
    }

    private function setPagesHtml($pageurl, $page_tpl)
    {
        $this->assign('page_vars', $this->M->page);
        $this->assign('page_url', $pageurl);
        $pagehtml = $this->fetch($page_tpl);
        $this->assign('page', $pagehtml);
        $this->pagestring = $pagehtml;
    }

    public function pageinfo($name, $content)
    {
        $this->pageinfo_data[$name] = $content;
    }
    public function checkLogin($return = false)
    {
        $member = session('member');
        if (!$member['id']) {
            if ($return === false) {
                $tourl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                session('loginto', $tourl);
                header('Location:/member/login.html');
                exit;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }
    public function boxpost()
    {
        $data = $this->_get('data');
        if (empty($data)) {
            $data = $this->_post('data');
        }
        $postring = explode('&amp;', $data);
        $post = array();
        foreach ($postring as $po) {
            $poitem = explode('=', $po);
            $post[$poitem[0]] = $poitem[1];
        }
        return $post;
    }
    public function errmsg($msg)
    {
        $this->assign('msg', $msg);
        $this->display('Public:boxnotice');
        exit;
    }
    public function sucmsg($msg)
    {
        $this->assign('status', 1);
        $this->assign('msg', $msg);
        $this->display('Public:boxnotice');
        exit;
    }
    protected function ajaxSuccess($message = '', $data = '', $type = 'JSON', $code = 0)
    {
        $this->ajaxReturn($data, $message, 1, $type, $this->pagestring, $code);
    }
    protected function ajaxError($message = '', $data = '', $type = 'JSON', $code = 0)
    {
        $this->ajaxReturn($data, $message, 0, $type, $this->pagestring, $code);
    }
    protected function ajaxAssign(&$result)
    {
        $result['msg'] = $result['info'];
    }
    public function gensaverule()
    {
        return time() . rand(100000, 999999);
    }
    public function upload($path)
    {
        import('@.ORG.Net.UploadFile');
        $upload = new UploadFile();
        $upload->maxSize = 3145728;
        $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');
        $upload->savePath = 'Upload/' . $path;
        $upload->saveRule = $this->gensaverule();
        if (!$upload->upload()) {
            $this->errorMsg = $upload->getErrorMsg();
            return false;
        } else {
            $info = $upload->getUploadFileInfo();
            return $info[0]['savepath'] . $info[0]['savename'];
        }
    }
    public function verifycheck($verify)
    {
        return $_SESSION['verify'] == md5($verify) ? true : false;
    }
    public function smscheck($smscode)
    {
        return $_SESSION['smscode'] == md5($smscode) ? true : false;
    }
    public function ajaxcheck($name, $content = null)
    {
        $ajaxcheck = session('ajaxcheck');
        if (!$content) {
            return $ajaxcheck[$name];
        } else {
            $ajaxcheck[$name] = $content;
            session('ajaxcheck', $ajaxcheck);
        }
    }

    public function javascript($function, $params = array())
    {
        exit('<script type="text/javascript">' . $function . '("' . implode('","', $params) . '");</script>');
    }
    

    /**
     * 判断是否在登录中
     *
     * @return bool true:在登录中,false:登录状态失效
     */
    protected function checkLoginedStatus()
    {
        $login_suc_data = $this->getLoginSucData();
        if (empty($login_suc_data)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取用户登录成功后的返回数据
     */
    protected function getLoginSucData()
    {
        return session($this->login_suc_tag);
    }

    /**
     * 设置用户登录成功后数据
     * @param $data array 从接口获取到的登录成功后的返回数据
     */
    protected function setLoginSucData($data)
    {
        session($this->login_suc_tag, $data);
    }

    /**
     * 销毁登录成功后的数据
     */
    protected function destroyLoginSucData()
    {
        session($this->login_suc_tag, null);
    }

    /**
     * curl 数据请求
     */
    public function curlpost($post_url = '', $post_params = array())
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $post_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    //标缓存连接
    public function redis_cache_connect()
    {
        if ($this->redis_cache) {
            return $this->redis_cache;
        }
        try {
            $REDIS_SERVER = C('REDIS_SERVER');
            $redis = new Redis();
            $redis->connect($REDIS_SERVER['HOST'], $REDIS_SERVER['PORT']);
            if( $REDIS_SERVER['REDIS_REDIS_AUTH'] ){
                $redis->auth($REDIS_SERVER['REDIS_REDIS_AUTH']);
            }
            $this->redis_cache = $redis;
            return $this->redis_cache;
        } catch (Exception $e) {
        }
    }
    
    /**
     * 从另三方接口查询手机号码归属地名称
     * 
     * @param string $mobile 手机号码
     * @return string 城市名
     */
    public function getMobileLocationNameByUrl($mobile)
    {
        $str = file_get_contents("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel={$mobile}");
        $html = iconv("gb2312", "utf-8//IGNORE", $str);
        $arr = explode(',', $html);
        $arr_item = explode(':', $arr[1]);
        $province = str_replace("'", '', $arr_item[1]);
        
        return $province;
    }

    /**
     * 生成系统密码
     * @param string $original 密码内容
     * @return string
     */
    protected function gen_password($original)
    {
        return md5($original . C('SECURE_KEY'));
    }
    
    /**
     * 发送手机短信
     * 
     * @param string $phone  需要发送的手机号码
     * @param string $send_content 需要发送的内容
     */
    protected function sendSms($phone, $send_content)
    {
        import('@.ORG.Util.SMS');
        SMS::send($phone, $send_content);
    }

    /**密码强度检测
     * @param string $string 检测的密码
     * @return int 1弱 2中 3强
     */
    function verifyStringStrong($string){
        $strength = 0;
        if(preg_match("/[0-9]/", $string)) {
            $strength ++;
        }
        if(preg_match("/[a-z|A-Z]/", $string)) {
            $strength ++;
        }
        if(preg_match('/[~|`|_|\-|+|=|\||*|!|@|#|$|%|^|&|(|)|{|}|\[|\]|\/|\\\\|\'|\"|<|>|,|\.|\?|:|;]+/', $string)) {
            $strength ++;
        }
        return $strength;
    }
	
    protected function  json_curlpost($url,$param,$header=array(),$type="POST"){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);//设置url
        //1)设置请求头
        array_push($header,'Content-Type:application/json');
        //设置为false,只会获得响应的正文(true的话会连响应头一并获取到)
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt ( $ch, CURLOPT_TIMEOUT,5); // 设置超时限制防止死循环
        //设置发起连接前的等待时间，如果设置为0，则无限等待。
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
        //将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //2)设备请求体
        if (count($param)>0) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($param));//全部数据使用HTTP协议中的"POST"操作来发送。
        }
        //设置请求头
        if(count($header)>0){
            curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
        }
        //上传文件相关设置
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);// 从证书中检查SSL加密算
        switch($type){
            case "GET":
                curl_setopt($ch,CURLOPT_HTTPGET,true);
                break;
            case "POST":
                curl_setopt($ch,CURLOPT_POST,true);
                break;
            case "PUT"://使用一个自定义的请求信息来代替"GET"或"HEAD"作为HTTP请求。这对于执行"DELETE" 或者其他更隐蔽的HTT
                curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"PUT");
                break;
            case "DELETE":
                curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"DELETE");
                break;
        }
        $res=curl_exec($ch);
        $result=json_decode($res,true);
        curl_close($ch);
        if(empty($result)){
            return $res;
        }else{
            return $result;
        }
    }

    //发送手机短信验证码
    public function ajaxSendSettleDefSms($mobile)
    {
        //开始发放短信
        import('@.ORG.Util.SMS');
        $sent = SMS::buildverify($mobile);
        if ($sent) {
            $this->ajaxSuccess('验证码已发送至您的手机：' . substr($mobile, -4) . '<br><br>本次验证码序号：' . $sent . '<br><br>请查收验证码内容并输入至"短信验证"框内');
        } else {
            $this->ajaxError('验证码发送失败（' . SMS::$errcode . '），请联系客服或重试');
        }
    }

    /**
     * 将数据导出为excel
     * @param array $titles 导出的excel表的标题
     * @param array $data_list 导出的excel表的内容
     * @param string $filename 导出保存的excel文件名
     * @param string $sheet_name 导出的excel活动表名（为空的话，则取文件名）
     */
    function exportExcel($titles = array(), $data_list = array(), $filename, $sheetname){
        //error_reporting(0);
        $objPHPExcel = new PHPExcel();
        //横向单元格标识
        $cellName   = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $xlsTitle   = $filename;
        $sheetname = empty($sheetname) ? $filename : $sheetname;
        $objSheet   = $objPHPExcel->getActiveSheet(); //获取当前活动sheet
        $objSheet->setTitle($sheetname); //给当前的活动sheet起个名称
        //设置表格表头
        $titlesLength = count($titles);
        //设置表格内容居中形式，换行
        $objSheet->getStyle("{$cellName[0]}:{$cellName[$titlesLength - 1]}")->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//文字居中
        $objSheet->getStyle("{$cellName[0]}:{$cellName[$titlesLength - 1]}")->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
        $objSheet->getStyle("{$cellName[0]}:{$cellName[$titlesLength - 1]}")->getAlignment()->setWrapText(true);// 单元格换行
        for ($i = 0; $i < $titlesLength; $i++) {
            $objSheet->setCellValue("{$cellName[$i]}1", $titles[$i]['name']);
            $objSheet->getColumnDimension("{$cellName[$i]}")->setAutoSize(false);
            $objSheet->getColumnDimension("{$cellName[$i]}")->setWidth($titles[$i]['cellWidth']);
        }
        //设置表格表头的背景色和边框
        $objSheet->getStyle("{$cellName[0]}1:{$cellName[$titlesLength - 1]}1")->applyFromArray(
            array(
                'fill' => array(
                    'type' => \PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => "ccffff")
                ),
                'borders' => array(
                    'allborders' => array(
                        'style' => PHPExcel_Style_Border::BORDER_THIN,
                        'color' => array('rgb' => '000000')
                    )
                )
            )
        );
        //设置表格表头的行高
        $objSheet->getRowDimension('1')->setRowHeight(30);
        foreach ($data_list as $key => $item) {
            //行号
            $rowIndex = $key + 2;
            for ($i = 0; $i < $titlesLength; $i++) {
                //单元格序号
                $cellIndex = $cellName[$i] . ($key + 2);
                //判断内容是否为图片
                $first4char = strtolower( substr($item[$i], 0,4) );
                $last3char = strtolower( substr($item[$i], -3) );
                if ( in_array( $last3char, array("jpg","peg","png","gif") ) && $first4char == "http" ) {
                    $imgPath = $item[$i];//获取图片路径
                    if ($last3char == 'jpg' || $last3char == 'peg') {
                        $img = @imagecreatefromjpeg($imgPath);
                    } else if ($last3char == 'png') {
                        $imgPath = $item[$i];//获取图片路径
                        $img = @imagecreatefrompng($imgPath);
                    } else if ($last3char == 'gif') {
                        $imgPath = $item[$i];//获取图片路径
                        $img = @imagecreatefromgif($imgPath);
                    }
                    $objDrawing = new \PHPExcel_Worksheet_MemoryDrawing();
                    $objDrawing->setImageResource($img);//图片格式
                    $objDrawing->setRenderingFunction(\PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT);//渲染方法
                    $objDrawing->setMimeType(\PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
                    $objDrawing->setHeight(100);//照片高度
                    $objDrawing->setWidth(100); //照片宽度
                    $objDrawing->setCoordinates($cellIndex);//图片要插入的单元格
                    $objDrawing->setOffsetX(5);//图片X轴偏移
                    $objDrawing->setOffsetY(5);//图片Y轴偏移
                    $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
                }else{
                    $objSheet->setCellValue($cellIndex, "\t{$item[$i]}\t");
                }
                $objSheet->getRowDimension($rowIndex)->setRowHeight(82); //设置行高
                //设置数据内容的边框
                $objSheet->getStyle("$cellName[$i]$rowIndex:$cellName[$i]$rowIndex")->applyFromArray(
                    array(
                        'borders' => array(
                            'allborders' => array(
                                'style' => PHPExcel_Style_Border::BORDER_THIN,
                                'color' => array('rgb' => '000000')
                            )
                        )
                    )
                );
            }
        }
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$filename.xls");
        header('Cache-Control: max-age=0');
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 上传Excel文件并读出Excel中的数据
     * @param bool $hava_titles Excel文件中是否有标题(默认第一行为标题)
     * @param int $sheet 指数据所在的sheet表序列
     * @return array 返回数组数据（title为excel中的标题，data_list为excel中的数据列表）
     */
    public function uploadExcelToData($hava_titles = true, $sheet = 0)
    {
        $img_src = $this->upload('');
        if ($img_src === false) return false;

        $upload_res = $this->readExeclData($img_src, $sheet);
        @unlink($img_src);
        if ($upload_res === false) return false;

        $titles = array();
        if ($hava_titles) {
            $titles = array_shift($upload_res);
        }
        return ['titles' => $titles, 'data_list' => $upload_res];
    }

    /**
     *  将excel数据导出为数组
     * @param string $file excel文件
     * @param string $sheet
     * @return string   返回解析数据
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     */
    public function readExeclData($filename = '', $sheet = 0){
        error_reporting(0);
        import('Vendor.PHPExcel.PHPExcel', EXTEND_PATH, '.php');

        $filename = iconv("utf-8", "gb2312", $filename);   //转码
        if(empty($filename) OR !file_exists($filename)) {
            $this->errorMsg = 'excel文件不存在!';
            return false;
        }
        $objRead = new PHPExcel_Reader_Excel2007();   //建立reader对象
        if(!$objRead->canRead($filename)){
            $objRead = new PHPExcel_Reader_Excel5();
            if(!$objRead->canRead($filename)){
                $this->errorMsg = '该文件不是一个有效的excel文件';
                return false;
            }
        }

        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');

        $obj = $objRead->load($filename);  //建立excel对象
        $currSheet = $obj->getSheet($sheet);   //获取指定的sheet表
        $columnH = $currSheet->getHighestColumn();   //取得最大的列号
        $columnCnt = array_search($columnH, $cellName);
        $rowCnt = $currSheet->getHighestRow();   //获取总行数

        $data = array();
        for($_row=1; $_row<=$rowCnt; $_row++){  //读取内容
            for($_column=0; $_column<=$columnCnt; $_column++){
                $cellId = $cellName[$_column].$_row;
                $cellValue = $currSheet->getCell($cellId)->getValue();
                if($cellValue instanceof PHPExcel_RichText){   //富文本转换字符串
                    $cellValue = $cellValue->__toString();
                }

                $data[$_row][$cellName[$_column]] = trim($cellValue);
            }
        }

        return $data;
    }

    /**
     * @param string $imageUrl 图片源地址
     * @param string $filename 图片名称
     * @param string $savePath 保存地址
     * @param int $percent 非固定像素等比缩放比例 0.3缩放30%
     * @param int $maxPx 固定像素等比缩放
     * @param false $resetColor 是否需要更改图片颜色
     */
    public function createGoodsThumbImage($imageUrl = "", $filename = "", $savePath = "", $percent = 0, $maxPx = 0, $resetColor = false){
        $ext = strtolower( substr($imageUrl, -3) );
        if( $ext != "jpg" && $ext != "peg" && $ext != "png" ){
            return null;
        }
        //判断目录是否存在，不存在则创建
        if( !is_dir($savePath) ){
            @mkdir($savePath, 0777);
        }
        list($width, $height) = getimagesize($imageUrl);
        $n_w = $width;
        $n_h = $height;
        if( $percent > 0 ){
            $n_w = $width * $percent;
            $n_h = $height * $percent;
        }
        //指定缩放出来的最大的宽度(也有可能是高度)
        if( $maxPx > 0 ){
            //根据最大值为300，算出另一个边的长度，得到缩放后的图片宽度和高度
            if($width > $height){
                $n_w = $maxPx;
                $n_h = $height * ( $maxPx / $width );
            }else{
                $n_h = $maxPx;
                $n_w = $width * ( $maxPx / $height );
            }
        }
        $new = imagecreatetruecolor($n_w, $n_h);
        if( $ext == "png" ) {
            $img = imagecreatefrompng($imageUrl);
        }else{
            $img = imagecreatefromjpeg($imageUrl);
        }
        if( $resetColor == true ){
            //随机更改图片颜色
            $color = $this->getRgb();
            //随机更改图片颜色
            $rgb1 = intval($color[0]);
            $rgb2 = intval($color[1]);
            $rgb3 = intval($color[2]);
            imagefilter($img, IMG_FILTER_COLORIZE, $rgb1, $rgb2, $rgb3);
        }
        imagecopyresized($new, $img, 0, 0, 0, 0, $n_w, $n_h, $width, $height);
        $newImageUrl = $savePath."/".$filename;
        if( $ext == "png" ) {
            imagepng($new, $newImageUrl);
        }else{
            imagejpeg($new, $newImageUrl);
        }
        imagedestroy($new);
        imagedestroy($img);
        return $newImageUrl;
    }

    /**
     * 随机获取RGB颜色值
     * @return string
     */
    public function getRgb(){
        $source = [
            "138 49 221",
            "42 152 221",
            "92 169 40",
            "115 221 173",
            "221 31 148",
            "57 226 51",
            "255 131 26",
            "2 80 49",
            "221 171 53",
            "221 0 103",
            "93 42 221",
            "221 20 28",
            "221 112 57"
        ];
        $key = array_rand($source,1);
        $rgb = $source[$key];
        $color = explode(" ",$rgb);
        return $color;
    }

    /**
     * 判单远程文件是否存在
     * @param $url
     * @return bool
     */
    public function checkRemoteFile($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_NOBODY, 1);
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if(curl_exec($ch)!==FALSE){
            return true;
        } else {
            return false;
        }
    }

    /**
     * 返回分类数组
     * @return array
     */
    public function getCategory($catId = 0){
        $key = "index_index_trademarks_category";
        $jsonData = $this->redis_cache->get($key);
        $list = json_decode($jsonData,true);
        if(empty($list)){
            $list = M("trademarks_category")->select();
            $this->redis_cache->setex($key, 60 * 60, json_encode($list));
        }
        if( $catId > 0 ){
            foreach ($list as $k => $v){
                if( $catId == $v['id'] ){
                    return $v['cate_name'];
                }
            }
        }else{
            return $list;
        }
    }

    /**
     * 获取图片数据
     * @param $brander
     * @param $type
     * @return string
     */
    public function getImageUrl($brander, $type){
        //没有彩图
        if (0 == $brander['picColor']) {
            //原图
            return "https://bbk-public.biaobiaoku.com/brand-pic/raw/" . $brander['picHash'] . ".jpg";
        }
        switch ($type) {
            //原图
            case 0:
                return "https://bbk-public.biaobiaoku.com/brand-pic/raw/" . $brander['picHash'] . ".jpg";
            //彩图
            default:
                return "https://bbk-public.biaobiaoku.com/brand-pic/color/" . $brander['picHash'] . ".png?v=0130";
        }
    }
}
?>